import { Next } from "koa";
import { AppCTX } from "../../types/koaExtend";
import { checkSpokesman } from "../../service/spokesmanService";
import Router from "koa-router";

const mw = async (ctx: AppCTX, next: Next) => {
  const reqUrl = ctx.request.url;
  console.log("brandSpokesmanChecker =>", reqUrl);
  if (reqUrl.startsWith("/spn")) {
    const { spokesmanId } = ctx.params;
    const userId = ctx.userId;
    const checkRet = await checkSpokesman(userId, spokesmanId);
    if (!checkRet) {
      ctx.throw(403, "not authorized, user is not must be a spokesman");
    }
  }
  await next();
};

export default mw;

export const createSpokesmanApiMWRouter = () => {
  const router = new Router();
  return router.use("/spn/:spokesmanId/", mw);
};
